package com.learning.concurrent.basic;



import java.util.ArrayList;
		import java.util.List;
import java.util.PriorityQueue;

/**
 * description:
 *
 * @author minghuiZhang
 * @date created in  10:47 2018/5/10
 * modified by
 */
public class WaitAndNotify {
	private volatile static List list = new ArrayList();

	public void add(){
		list.add("bjsxt");
	}
	public int size(){
		return list.size();
	}

	public static void main(String[] args) {

		final WaitAndNotify list2 = new WaitAndNotify();
		final Object lock = new Object();
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					synchronized (lock) {
						System.out.println("t1启动..");
						for(int i = 0; i <10; i++){
							list2.add();
							System.out.println("当前线程：" + Thread.currentThread().getName() + "添加了一个元素..");
							Thread.sleep(500);
							if(list2.size() == 5){
								System.out.println("已经发出通知..");
								lock.notify();
							}
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "t1");

		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					System.out.println("t2启动..");
					if(list2.size() != 5){
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.out.println("当前线程：" + Thread.currentThread().getName() + "收到通知线程停止..");
					throw new RuntimeException();
				}
			}
		}, "t2");
		t2.start();
		t1.start();

	}
}

/*
思路整理：
		线程t1,t2。t1的run方法执行count++操作，当count=5时，通知t2线程停止首先启动t2线程

		对于t1
		if (count == 5){
		lock.notify()
		}
		对于t2
		if (count != 5){
		lock.wait()
		}

		throw new Exception();

		首先启动t2线程，t2先获得lock，判断count是否等于5，如果不等于，lock.wait()，释放lock,t1开始执行，
		当count增加到5时，执行lock.notify()，因为notify()不释放锁，所以t2直到t1执行完程序释放锁之后，再停止线程

		缺点：这种方式在存在缺陷，t2必须在t1执行完之后，才能抛出异常，实时性不好。
		改进方法见		WaitAndNotifyAdvanced.java文件

*/
